package com.bxl.chooser.server;

import com.bxl.chooser.bean.ChooseMsg;
import com.bxl.chooser.bean.ChooseResponseMsg;
import com.bxl.chooser.context.ChooserContext;
import com.bxl.chooser.oper.IOperSv;
import com.bxl.chooser.oper.OperDefine;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.PackageMsg;
import com.bxl.netty.rpc.common.message.RpcHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class ChooseServerHandler extends SimpleChannelInboundHandler<PackageMsg<ChooseMsg>> {
    private ChooseServerContext context;
    private ChooserContext chooserContext;

    public ChooseServerHandler() {

    }

    public ChooseServerHandler(Context context) {
        assert context == null;
        if(context instanceof  ChooseServerContext){
            this.context = (ChooseServerContext)context;
            this.chooserContext = this.context.getChooserContext();
        }
        
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PackageMsg<ChooseMsg> msg) throws Exception {
        int flag = 0;//成功
        ChooseResponseMsg res = null;
        try {
            IOperSv<ChooseResponseMsg> oper = OperDefine.getOper(msg.getHeader().getFlag());
            res = oper.oper(msg, this.chooserContext);
        } catch (Exception e) {
            flag = 1;
            e.printStackTrace();//失败
        }
        RpcHeader header = new RpcHeader();
        header.setFlag(flag);
        header.setRequestID(msg.getHeader().getRequestID());
        PackageMsg<ChooseResponseMsg> rtnMsg = new PackageMsg<ChooseResponseMsg>();
        rtnMsg.setHeader(header);
        rtnMsg.setContent(res);
        ctx.writeAndFlush(rtnMsg);

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception{
        System.out.println(ctx.channel().remoteAddress());
        ctx.disconnect();
    }

}
